import React from 'react'
import { useSelector,useDispatch} from 'react-redux'
import { selectAll } from '../../store/actions/todo'
import TodoItem from '../TodoItem'


export default function TodoMain() {
   // 持久化的思路
  // 1. 一上来获取数据的时候，本地有，就用本地的，本地没有就从 Redux 里面获取
  // 2. list 变化就存储数据到本地
  const list = useSelector((state) => {
    if(state.filter === 'active'){
      return state.todo.filter((item) => item.done === false)
    } else if( state.filter === 'completed'){
      return state.todo.filter((item) => item.done === true)
    }else{
      return state.todo
    }
  })
  // !确定全选的状态，根据所有的单选的状态来确定
  const  dispatch = useDispatch()
  const isCheckAll = list.every((item) => item.done)
  // !全选操作
  const handleChangeAll = () => dispatch(selectAll(!isCheckAll))

  return (
    <section className='main'>
      <input id='toggle-all' 
      className='toggle-all'
       type='checkbox' 
       checked={isCheckAll}
       onChange={handleChangeAll}
       />
      <label htmlFor='toggle-all'>Mark all as complete</label>
        {/* // #2. 用 currentID 和 item.id 进行比较，如果是 true 就应用 editing class */}
      <ul className='todo-list'>
        {list.map((item) => (
         <TodoItem key={item.id} item={item}></TodoItem>
        ))}
      </ul>
    </section>
  )
}